package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketLog;
import com.cskaoyan.market.service.AdminLogService;
import com.cskaoyan.market.service.impl.AdminLogServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @description: 日志管理
 * @author: 刘国兴
 **/
@WebServlet("/admin/log/*")
public class AdminLogController extends HttpServlet {

    private AdminLogService logService = new AdminLogServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp){
        dispatchRequest(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp){
        dispatchRequest(req, resp);
    }

    /**
     * @author 刘国兴
     * @description 分发请求
     */
    private void dispatchRequest(HttpServletRequest req, HttpServletResponse resp) {
        String op = req.getPathInfo();
        try {
            switch (op) {
                case "/list":
                    //列表显示与查询功能
                    getLogList(req, resp);
                    break;
                default:
                    //重定向交给其他servlet处理这个请求
                    resp.sendRedirect(req.getRequestURI());

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @author 刘国兴
     * @description 获取列表
     */
    private void getLogList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //第一步：获取req中&连接的参数page&limit&name&sort&order
        Map<String, String[]> parameterMap = req.getParameterMap();
        //第二步：调用service处理业务，并把参数传递下去，获取logList
        List<MarketLog> logList = logService.list(parameterMap);
        //第三步：处理成标准响应的格式然后响应回去
        Object okList = ResponseUtil.okList(logList);
        resp.getWriter().println(JacksonUtil.writeValueAsString(okList));
    }

}